<?php
namespace app\backman\controller;
use app\backman\model\Meal;
use \app\common\controller\AuthBack;
use app\common\model\Detection as DetectionItem;
use app\common\model\DetectionSon;
use app\common\model\Goods;
use app\common\model\Customer;
use think\Db;
use think\facade\App;
use think\facade\Env;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Intervention\Image;
use GuzzleHttp;
require_once App::getRootPath().'/extend/PHPExcel/PHPExcel.php';


class Detection extends AuthBack
{


	public function initialize()
	{
		parent::initialize();
	}

	public function index()
	{
		$model       = new DetectionItem;
		$limit       = isset($_GET['limit']) ? $_GET['limit'] : '20';
		$like        = isset($_GET['like']) ? $_GET['like'] : '';
		$customer_id = isset($_GET['customer_id']) ? $_GET['customer_id'] : '';
		$goods_id    = isset($_GET['goods_id']) ? $_GET['goods_id'] : '';
		$where       = [];
		if ($like) {
			$where[] = ['remark', 'like', "%{$like}%"];
		}
		if ($customer_id) {
			$where[] = ['customer_id', '=', $customer_id];
		}
		if ($goods_id) {
			$where[] = ['goods_id', '=', $goods_id];
		}
		if (!empty(input('start_time')) && !empty(input('end_time'))) {
			$where[] = ['timestamp', 'between', input('start_time') . ',' . input('end_time')];
		} else {
			if (!empty(input('start_time'))) {
				$where[] = ['timestamp', '>=', input('start_time')];
			}
			if (!empty(input('end_time'))) {
				$where[] = ['timestamp', '<=', input('end_time')];
			}
		}

		$totalNum = DetectionItem::where($where)->count();
		if (request()->isAjax()) {
			$page      = isset($_GET['page']) ? $_GET['page'] : '1';
			$limit     = isset($_GET['limit']) ? $_GET['limit'] : '20';
			$startNum  = ($page - 1) * $limit;
			$totalPage = ceil($totalNum / $limit);

			if (!empty(input('title'))) {
				$where[] = ['detection_sn|name|content', 'like', '%' . input('title') . '%'];
			}

			$list = DetectionItem::where($where)->limit($startNum . ',' . $limit)->order('id desc')->select();

			if (empty($list)) {
				return json(['code' => 0, 'data' => [], 'total' => $totalPage, 'count' => $totalNum]);
			} elseif ($page > $totalPage) {
				return json(['code' => 0, 'data' => [], 'total' => $totalPage + 1, 'count' => $totalNum]);
			} else {
				$nList = [];
				if (!empty($list)) {
					foreach ($list as $k => $vo) {
						$nList[$k]                  = $vo;
						$nList[$k]['goods_text']    = $vo['goods_id']['text'];
						$nList[$k]['customer_name'] = $vo['customer_id']['text'];
						$nList[$k]['number_line']   = str_pad($vo['start_num'],8,"0",STR_PAD_LEFT) . '-' . str_pad($vo['end_num'],8,"0",STR_PAD_LEFT);
						$nList[$k]['op']            = url('option', ['id' => $vo['id']]);
						$nList[$k]['cp']            = url('copy', ['id' => $vo['id']]);
						$nList[$k]['lc']            = url('lcindex', ['id' => $vo['id']]);
					}
				}
				$return = [
					'code'  => 0,
					'msg'   => '',
					'count' => $totalNum,
					'data'  => $nList
				];
				return json($return);
			}
		} else {
			$goods    = Db::name('goods')->where('status', 1)->select();
			$customer = Db::name('customer')->where('status', 1)->select();
			$this->assign('goods', $goods);
			$this->assign('customer', $customer);
			$this->assign('totalNum', $totalNum);
			return view();
		}
	}


	/**
	 * 分配记录删除
	 */
	public function del()
	{
		$count = DB::name('order')->where('detection_id', $this->data['id'])->count();
		if ($count) {
			return $this->error('已有核销记录，无法删除');
		} else {
			AdminLog($this->admin['id'], '删除分配记录【' . $this->data['id'] . '】信息');
			$res = DB::name('detection')->where('id', $this->data['id'])->delete();

			if ($res) {
				return $this->success('操作成功', url('index'));
			} else {
				return $this->error('删除失败');
			}
		}

	}


	/**
	 * 二维码分配管理 添加/修改
	 * @param int $id
	 * @return \think\response\View|void
	 */
	public function option($id = 0)
	{
		if (!request()->isPost()) {

			$info = DetectionItem::get($id);
			// 商品列表
			$goods    = Goods::where('status', 1)->field('id, title')->order('timestamp desc')->select();
			$customer = Customer::where('status', 1)->field('id, customer_name')->order('timestamp desc')->select();

			$this->assign('info', $info);
			$this->assign('goods', $goods);
			$this->assign('customer', $customer);

			return view();
		} else {
			$obj = new DetectionItem();

			if ($this->data['id']) {
				// 编辑
				AdminLog($this->admin['id'], '修改二维码记录【' . $this->data['start_num'] . '-' . $this->data['end_num'] . '】信息');
				$state = $obj->saveData($this->data, 'edit');
			} else {
				// 新增
				AdminLog($this->admin['id'], '新增二维码记录【' . $this->data['start_num'] . '-' . $this->data['end_num'] . '】');
				$state = $obj->saveData($this->data);
			}
			if ($state) {
				return $this->success('操作成功', url('index'));
			} else {
				return $this->error($obj->getError());
			}
		}
	}


	public function load_excel(){

		$like        = isset($_GET['like']) ? $_GET['like'] : '';
		$customer_id = isset($_GET['customer_id']) ? $_GET['customer_id'] : '';
		$goods_id    = isset($_GET['goods_id']) ? $_GET['goods_id'] : '';
		$where       = [];
		if ($like) {
			$where[] = ['remark', 'like', "%{$like}%"];
		}
		if ($customer_id) {
			$where[] = ['customer_id', '=', $customer_id];
		}
		if ($goods_id) {
			$where[] = ['goods_id', '=', $goods_id];
		}
		if (!empty(input('start_time')) && !empty(input('end_time'))) {
			$where[] = ['timestamp', 'between', input('start_time') . ',' . input('end_time')];
		} else {
			if (!empty(input('start_time'))) {
				$where[] = ['timestamp', '>=', input('start_time')];
			}
			if (!empty(input('end_time'))) {
				$where[] = ['timestamp', '<=', input('end_time')];
			}
		}

		$list = DetectionItem::where($where)->order('id desc')->select();


		$nList = [];
		if (!empty($list)) {
			foreach ($list as $k => $vo) {
				$nList[$k]                  = $vo;
				$nList[$k]['goods_text']    = $vo['goods_id']['text'];
				$nList[$k]['customer_name'] = $vo['customer_id']['text'];
				$nList[$k]['number_line']   = str_pad($vo['start_num'], 8, "0", STR_PAD_LEFT) . '-' . str_pad($vo['end_num'], 8, "0", STR_PAD_LEFT);
				$nList[$k]['op']            = url('option', ['id' => $vo['id']]);
				$nList[$k]['cp']            = url('copy', ['id' => $vo['id']]);
				$nList[$k]['lc']            = url('lcindex', ['id' => $vo['id']]);
			}

			$excelName = 'FP' . date('YmdHis');
			$this->exportExcel($nList, $excelName);


			exit();
		}

		$excelName = 'FP' . date('YmdHis');
		$this->exportExcel($nList, $excelName);


		exit();
	}



	public function exportExcel($data, $name){
		$objPHPExcel = new \PHPExcel();  //实例化  相当于在桌面新建一个excel
		// 表头
		$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A1', '分配产品')
			->setCellValue('B1', '业务员名称')
			->setCellValue('C1', '分配数量')
			->setCellValue('D1', '流水号范围')
			->setCellValue('E1', '备注')
			->setCellValue('F1', '分配时间');
		//设置内容水平居中
		$objPHPExcel->setActiveSheetIndex(0)->getStyle('A')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
		// 设置个表格宽度
		$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(24);
		//设置单元格自动宽度
		$objPHPExcel->getActiveSheet()->getColumnDimension("A")->setAutoSize(true);
		// 内容
		for ($i = 0, $len = count($data); $i < $len; $i++) {
			$objPHPExcel->getActiveSheet(0)->setCellValue('A' . ($i + 2), $data[$i]['goods_text']);     //产品名称
			$objPHPExcel->getActiveSheet(0)->setCellValue('B' . ($i + 2), $data[$i]['customer_name']);   //业务员姓名
			$objPHPExcel->getActiveSheet(0)->setCellValue('C' . ($i + 2), $data[$i]['count_num']);   //分配数量
			$objPHPExcel->getActiveSheet(0)->setCellValue('D' . ($i + 2), $data[$i]['number_line']);   //流水号范围
			$objPHPExcel->getActiveSheet(0)->setCellValue('E' . ($i + 2), $data[$i]['remark']);   // 备注
			$objPHPExcel->getActiveSheet(0)->setCellValue('F' . ($i + 2), $data[$i]['timestamp']);   //分配时间

		}
		$objPHPExcel->getActiveSheet()->getColumnDimension('c')->setWidth(20);
		$objPHPExcel->getActiveSheet()->setTitle('User');
		$objPHPExcel->setActiveSheetIndex(0);
		ob_end_clean();//清楚缓存区，解决乱码问题
		header("Pragma:public");
		header("Content-Type:application/x-msexecl;name=\"{$name}.xlsx\"");
		header("Content-Disposition:inline;filename=\"{$name}.xlsx\"");
		$objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
		$objWriter->save('php://output');
		exit;
	}

}